<template>
	<view class="container">
		<cu-custom  :isBack="true">
			<block slot="backText"><text style="color:#fff">返回</text></block>
			<block slot="content">
				<text style="color:#fff">权限设置</text>
			</block>
		</cu-custom>
		
		<view class="page-form" style="width:92%;float:left;clear:both;margin-left:4%;height:60vh;padding:50rpx 15rpx;margin-top:60rpx;">
            <view style="width:100%;height:80rpx;float:left;margin-bottom:20rpx;border-bottom:#eee 1px solid;">
                <text style="float:left;font-size:35rpx;line-height:60rpx;">允许安装应用</text>
				
                <u-button style="float:right;font-size:27rpx;width:80rpx;" size="medium" type="primary" @click="handleCheckRequestInstallPackages(1)">查看</u-button>
				
				<u-icon name="info-circle-fill" v-show="!isOpenInstallPackages" style="float:right;margin-right:6px;color:#ff0000;font-size:23px;margin-top:5px;"></u-icon>
            </view>
            
			<view style="width:100%;height:80rpx;float:left;margin-bottom:20rpx;border-bottom:#eee 1px solid;">
                <text style="float:left;font-size:35rpx;line-height:60rpx;">通话自动录音权限</text>
                <u-button style="float:right;font-size:27rpx;width:80rpx;" size="medium" type="primary" @click="handleCheckAutoRecord()">查看</u-button>
            </view>
            
            <view style="width:100%;height:80rpx;float:left;margin-bottom:10rpx;border-bottom:#eee 1px solid;">
                <text style="float:left;font-size:35rpx;line-height:60rpx;">录音读取权限</text>

                <u-button style="float:right;font-size:27rpx;width:80rpx;" size="medium" type="primary" @click="handleCheckFileRole()">查看</u-button>
                
                <u-button style="float:right;font-size:27rpx;width:80rpx;margin-right:20rpx;" size="medium" type="primary" @click="handleGetRecord()">读取测试</u-button>
            </view>
            
            <view style="width:100%;height:200rpx;oveflow:hidden;overflow-y:auto;float:left;margin-bottom:10rpx;background-color: #eee;border-radius: 20rpx;padding:20rpx;" v-if="recordList != ''">
                {{recordList}}
            </view>
			
			<!-- 操作说明 -->
			<view style="width:100%;height:80rpx;float:left;margin-bottom:10rpx;" v-if="helpData != ''">
			    <text style="float:left;font-size:35rpx;line-height:60rpx;">{{helpTitle}}</text>
			</view>
			
			<view style="width:100%;height:200rpx;oveflow:hidden;overflow-y:auto;float:left;margin-bottom:10rpx;background-color: #eee;border-radius: 20rpx;padding:20rpx;" v-if="helpData != ''">
			    <rich-text :nodes="helpData"></rich-text>
			</view>
		</view>
		
		<u-toast ref="uToast" />
	</view>
</template>
<script>	
	import {
		mapState,
		mapGetters
	} from "vuex";
	
	import {getHelpData} from "@/api/index";
	
	const callModule = uni.requireNativePlugin("leven-call-CallModule");

	export default {
		data() {
			return {
				formData: {
					call_type:0
				},
				callTypeData: [{
					text: '自动',
					value: 0,
					content:"自动拨打拨号盘中的号码，如手机是双卡，如未在手机系统中设置默认拨号卡，则无法实现自动拨号。"
				}, {
					text: '手动',
					value: 1,
					content:"手动模式则直接跳转到手机拨号盘，需要手动外呼。"
				}],
				
				currentCallType: 0,
				currentContent:"自动拨打拨号盘中的号码，如手机是双卡，如未在手机系统中设置默认拨号卡，则无法实现自动拨号。",
				
				currentData:{},

				rules: {},
                
                recordList:"",
				helpData:"",
				helpTitle:"",
				isOpenInstallPackages:true

			}
		},
		computed: {
			...mapGetters(["userInfo","callType"]),
			...mapState({
				callType: state => state.app.callType
			} )
		},
		onLoad(option) {
			console.log("setting onLoad");
		},
		onShow(){
	
			//检测是否开记安装未知来源应用
			if (plus.os.name !== 'Android' || parseInt(plus.os.version) < 8) {
			    this.isOpenInstallPackages = true;
			}else{
				const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
				const activity = plus.android.runtimeMainActivity();
				const packageManager = activity.getPackageManager();
			
				// 3. 调用原生方法检测权限
				const canInstall = packageManager.canRequestPackageInstalls();
				  
				console.log("caninstall",canInstall);
				
				this.isOpenInstallPackages = canInstall;
			}
		},
		methods: {
			handleCheckAutoRecord(){

				

				    // const audioPermission = "android.permission.RECORD_AUDIO";
				    
				    // // 调用安卓原生权限申请
				    //     plus.android.requestPermissions(
				    //       [audioPermission],
				    //       (result) => {
							 //  console.log("result",result);
				    //         if (result.granted.length > 0) {
				    //           // 用户允许权限
							 //  console.log("录音权限已开启");
				    //           // uni.showToast({ title: "录音权限已开启" });
				    //           // this.startRecording();
				    //         } else if (result.deniedAlways.length > 0) {
				    //           // 用户永久拒绝（勾选"不再询问"）
							 //  console.log("权限被禁用");
				    //           // uni.showModal({
				    //           //   title: "权限被禁用",
				    //           //   content: "请在手机设置中开启录音权限",
				    //           //   success: () => {
				    //           //     // 跳转应用权限设置页
				    //           //     // this.openAppSettings();
				    //           //   }
				    //           // });
				    //         } else {
								// console.log("需要录音权限才能使用该功能");
				    //           // 用户临时拒绝
				    //           // uni.showToast({ 
				    //           //   title: "需要录音权限才能使用该功能", 
				    //           //   icon: "none" 
				    //           // });
				    //         }
				    //       },
				    //       (error) => {
				    //         console.error("权限申请失败:", error);
				    //       }
				    //     );
				
				

				callModule.toCallAutoRecorderPage(res => {
				    console.log("toCallAutoRecorderPage",res);
				});
            },
            
            handleCheckFileRole(){
                callModule.toAllFilesPermissionPage(res => {
                    console.log("toAllFilesPermissionPage",res);
                });
            },
			
            handleCheckRequestInstallPackages(type){
				let _this = this;
                const systemInfo = uni.getSystemInfoSync(); //获取系统信息，
				
                if (systemInfo.platform === 'android') {
                    const main = plus.android.runtimeMainActivity();
                    const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
                    const Build = plus.android.importClass('android.os.Build');
                    
                    console.log("build",Build,Build.VERSION,Build.VERSION.SDK_INT);
                    
                    // Android 8.0+ 需要动态请求权限
                    if (Build.VERSION.SDK_INT >= 26) {
                      const hasPermission = main.checkSelfPermission('android.permission.REQUEST_INSTALL_PACKAGES') == PackageManager.PERMISSION_GRANTED;
                      
                      console.log("haspermission",hasPermission,main.checkSelfPermission("android.permission.REQUEST_INSTALL_PACKAGES"),PackageManager.PERMISSION_GRANTED);
                      
                      if (!hasPermission) {
						  _this.isOpenInstallPackages = false;
							if(type == 1){
								// 跳转到系统设置页面引导用户开启权限
								const Intent = plus.android.importClass('android.content.Intent');
								const Uri = plus.android.importClass('android.net.Uri');
								const intent = new Intent('android.settings.MANAGE_UNKNOWN_APP_SOURCES', 
								  Uri.parse('package:' + main.getPackageName())
								);
								main.startActivityForResult(intent, 0);
							}
                      }else{
						  _this.isOpenInstallPackages = true;
					  }
                    }
                }
            },
            
            handleGetRecord(){
                // let one_file_name = "";
                
                // 获取当前时间
                const now = new Date();
            
                // 当天的开始时间（00:00:00.000）
                const startOfDay = new Date(now);
                startOfDay.setHours(0, 0, 0, 0); // 设置小时、分钟、秒、毫秒为0
            
                // 当天的结束时间（23:59:59.999）
                const endOfDay = new Date(startOfDay);
                endOfDay.setDate(endOfDay.getDate() + 1); // 设置为明天的00:00:00.000
                endOfDay.setTime(endOfDay.getTime() - 1); // 减1毫秒得到今天的最后一刻
                
                console.log("setting time",startOfDay.getTime(),endOfDay.getTime());
                
                callModule.getRecorderFiles({
                  //录音时间段
                  times: [startOfDay.getTime(), endOfDay.getTime()]
                }, res_record => {
                  // this.writeLog(JSON.stringify(res))
                  console.log("callmodule params");
                  console.log("callmodule");
                  console.log(res_record.data.files.length);
                  console.log(res_record.code);
                  
                  if(res_record.code == 0 && res_record.data.files.length > 0){
                	  console.log(res_record.data);
                	  console.log(res_record.data.files);
                      
                      this.recordList = JSON.stringify(res_record.data.files);
                  }
                });
                
                
                // 跳转到电池优化设置页

                  // const Intent = plus.android.importClass('android.content.Intent');
                  // const PowerManager = plus.android.importClass('android.os.PowerManager');
                  // const intent = new Intent(PowerManager.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                  // intent.setData(plus.android.invoke('android.net.Uri', 'parse', 'package:' + plus.android.runtimeMainActivity().getPackageName()));
                  // plus.android.runtimeMainActivity().startActivity(intent);
                
            },
			
			//获取手机操作说明
			initData(){
				// this.handleCheckRequestInstallPackages(0);
				
				  
				//获取手机系统信息
				let sys_info = uni.getSystemInfoSync();
				
				console.log("sys_info");
				console.log(sys_info);
				
				getHelpData(sys_info).then(res=>{
					console.log("gethelpdata res",res);
					
					if(res.data.code == 200){
						this.helpTitle = res.data.data.title;
						this.helpData = res.data.data.content;
					}
				}).catch(er=>{
					console.log("gethelpdata er",er);
				});
			}
		},

		onReady() {
			//this.$refs.uForm.setRules(this.rules);
			console.log("setting onready");
			
			this.initData();
		}
	}
</script>
<style>
.container {
	width: 100%;
	color: #333333;
	background-image: linear-gradient(to bottom, #075AFF, #ffffff);
	background-size: 100% 45%;
	background-repeat: no-repeat;
	background-position: top center;
	overflow-y: scroll;
}
</style>